import {reqshopCartList,reqCheckCart,reqDeleteCart} from "@/api"

const actions={

  async reqshopCartList({commit}){
    //请求购物车的数据
    const result = await reqshopCartList()
    if(result.code == 200){
      commit('REQSHOPCARTLIST',result.data)
    }
  },
    //切换商品的选中状态
    async reqCheckCart(context,{skuId,isChecked}){
       const result = await reqCheckCart(skuId,isChecked)
       if(result.code==200){
        return Promise.resolve("ok")
       }else {
        return Promise.reject(new Error('fail'))
       }
    },

    //全选与全不选
    reqAllCheckCart({dispatch,getters},isChecked){
      let AllPromise = []
      getters.cartList.cartInfoList.forEach(element => {
             const promise = dispatch('reqCheckCart',{skuId:element.skuId,isChecked})
              AllPromise.push(promise)
        });
        return Promise.all(AllPromise)
    },

    //删除商品
     async reqDeleteCart({commit},{skuId}){
        const result = await reqDeleteCart(skuId)
        if(result.code == 200) {
          return Promise.resolve('ok')
        }else{
          return Promise.reject(new Error('fail'))
        }
    }
}
const mutations={
  REQSHOPCARTLIST(state,shopCartList){
    state.shopCartList = shopCartList
  }
}
const state={
  shopCartList:[]
}
const getters = {
  cartList(state){
    return state.shopCartList[0] || {}
  }
}

export default {
  namespaced:true,
  actions,
  mutations,
  state,
  getters
}